<?php

namespace App\Http\Controllers\Auth;

use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Lrental\Passport\PassportClient;
use Hyn\Tenancy\Environment;

class OauthController extends Controller
{
    public function login()
    {
        $tenancy = app(Environment::class);
        $hostName = $tenancy->hostname();
        $tokenRequestURL = "http://" .$hostName->fqdn . config('passport.passport_oauth_token_url');
        $http = new Client();
        $pClient = PassportClient::where('password_client', '=', true)
            ->first();
        try {
            $response = $http->post($tokenRequestURL, [
                'headers' => [
                    'Accept' => 'application/json'
                ],
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => $pClient->id,
                    'client_secret' => $pClient->secret,
                    'username' => request()->get('username'),
                    'password' => request()->get('password'),
                    'scope' => '*',
                ],
            ]);
        } catch (\Exception $e) {
            throw $e;
            return response()->json(json_decode($e->getResponse()->getBody()->getContents(), true), 401);
        }
        return json_decode((string)$response->getBody(), true);
    }

    public function logout()
    {
        auth()->user()->token()->delete();
        return response()->json("logout success");
    }
}
